import datetime

from django.db import models

from sportsground.utils.baseModels import BaseModels, IntegerChoices


class Time():
    def __init__(self, t):
        self.id = t.get('id')
        self.startTime = t.get('startTime')
        self.endTime = t.get('endTime')
        self.price = t.get('price')
        self.capacity = t.get('capacity')
        self.reserved = t.get('reserved')

    def Info(self):
        """ 格式化 """
        return {
            "id": self.id,
            "startTime": self.startTime,
            "endTime": self.endTime,
            "price": self.price,
            "capacity": self.capacity,
            "reserved": self.reserved,
        }


class VenueSportYard(BaseModels):
    class Meta():
        db_table = 'venue_sport_yard'
        verbose_name = '运动场地'
        verbose_name_plural = verbose_name

    class Type(IntegerChoices):
        Indoor = 1, "室内"
        Outdoor = 2, "室外"

    name = models.CharField(max_length=20, verbose_name="名称")
    type = models.IntegerField(choices=Type.choices, default=Type.Indoor, verbose_name="类型")
    message = models.CharField(max_length=200, verbose_name="概述")
    readme = models.CharField(max_length=200, verbose_name="入馆须知")
    venueSport = models.ForeignKey(to="VenueSport", on_delete=models.CASCADE, verbose_name="馆场运动")

    time = models.JSONField(default=list, verbose_name="时间表")
    nextTime = models.JSONField(default=list, verbose_name="未来时间表")
    default = models.JSONField(default=list, verbose_name="默认每日")

    @classmethod
    def create(cls, sport, type, name=None, default={}, readme="", message=""):
        """ 创建 """
        yard = cls(venueSport=sport, type=type, name=name, message=message, readme=readme, default=default)
        yard.time = [[] for _ in range(7)]
        yard.save()
        return yard

    def Info(self):
        self.update()
        return {
            "id": self.id,
            "name": self.name,
            "type": self.type,
            "message": self.message,
            "readme": self.readme,
            "sport": self.venueSport.Info(),
            "time": self.time,
            "default": self.default,
        }

    def update(self):
        """ 更新时间 """
        today = datetime.date.today()
        lastDay = self.updateTime.date()
        days = (today - lastDay).days

        time = self.time
        for i in range(days):
            time.append(self.default)
        self.time = time[-7:]
        self.save()

    def getTime(self, index, id):
        """ 获取时间 """
        t = self.time[index]
        for item in t:
            if item.get('id') == id:
                return Time(item)
